<?php

namespace app\controller\user;

use app\BaseController;
use app\common\library\Jwt;
use app\model\user\IndexModel;
use app\validate\user\Index;
use think\exception\ValidateException;
use think\response\Json;

class IndexController extends BaseController
{
    public function login(): Json
    {
        $data = $this->request->post();

        try {
            $validate = validate(Index::class)->scene('login');
            if (!$validate->check($data)) {
                return json(result()->setMsg('参数验证失败')->fail());
            }
        } catch (ValidateException $e) {
            return json(result()->setMsg($e->getMessage())->fail());
        }
        // 账号获取和密码校验
        $user = (new IndexModel())->getUserData($data);
        if (empty($user)) {
            return json(result()->fail(result()::ACCOUNT_ERR));
        }
        if (!password_verify($data['password'], $user['password'])) {
            return json(result()->fail(result()::PASSWORD_ERR));
        }
        // 创建令牌
        $token = Jwt::instance()->createJwtToken($this->tokenClaimData($user));
        return json(result()->success(array('token' => $token)));
    }

    private function tokenClaimData(array $data): string
    {
        return json_encode(array('user_id' => $data['id']), JSON_UNESCAPED_UNICODE);
    }

    public function logout(): Json
    {
        return json(result()->success());
    }
}
